from os import CLD_CONTINUED
from django.core import paginator
from django.shortcuts import render
from rest_framework.views import APIView
import simplejson as json
import requests as req
from yushiapi.utils import * 
from yushiminiapp.settings import APPID,SECRET
from yushiapi.models import *
from yushiapi.forms import * 
from django.core.paginator import Paginator,PageNotAnInteger,EmptyPage
# Create your views here.


class YushiUserAPIView(APIView):

    def get(self,request,*args,**kwargs):
        code = request.GET.get("code")
        #####################temp###########################
        open_id = request.GET.get("open_id")
        user = YuShiUser.objects.filter(union_id=open_id).first()
        if not user:
            yushi_id = getYushiAccount()
            print(yushi_id)
            user = YuShiUser.objects.create(union_id=open_id,yushi_id=yushi_id) 
        request.session['union_id'] = user.union_id
        return resultResponse()
        #####################temp###########################
        if not code :
            return resultResponse(202)
        try:
            url = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code"
            response = req.get(url%(APPID,SECRET,code))
            resJson = json.loads(response.text)
            open_id = resJson.get("openid")
            sesssion_key = resJson.get("session_key")
            if not open_id or not sesssion_key:
                return resultResponse(203)
            user = YuShiUser.objects.filter(union_id=open_id).first()
            if not user:
                yushi_id = getYushiAccount()
                user = YuShiUser.objects.create(union_id=open_id,yushi_id=yushi_id) 
            request.session['union_id'] = user.union_id 
            request.session['session_key'] = sesssion_key
            return resultResponse()
        except:
            return resultResponse(700,"WeXin Server Error")
        

    def post(self,request,*args, **kwargs):
        union_id = request.session.get("union_id",None)
        nick_name = request.data.get("nick_name",None)
        if not nick_name:
            return resultResponse(700,"no nick_name")
        YuShiUser.objects.filter(union_id=union_id).update(nick_name=nick_name)
        return resultResponse()

class AuthenticationAPIView(APIView):

    def __create_role(self):
        Role.objects.create(name="teacher")
        Role.objects.create(name="org")

    def post(self,request,*args, **kwargs):
        # self.__create_role()
        _type = request.data.get("_type",None)
        if not _type :      
            return resultResponse(700,"no _type")
        union_id = request.session.get("union_id")
        yushi_user = YuShiUser.objects.get(union_id=union_id)
        if yushi_user.role:
            return resultResponse(700,"Already auth")
        if _type == "teacher":
            formRes = TeacherForm(request.POST)
            if formRes.is_valid():
                tea = Role.objects.get(name="teacher")
                teacher_data = formRes.cleaned_data 
                teacher_data["yushi_user"] = yushi_user 
                avator = request.FILES.get("avator",None)
                teacher_data["avator"] = avator
                yushi_user.role = tea
                Teacher.objects.create(**teacher_data)
            else:
                return resultResponse(700,formRes.errors)
        else:
            formRes = Organization(request.POST)
            if formRes.is_valid():
                org_data = formRes.cleaned_data 
                org_data["yushi_user"] = yushi_user
                logo = request.FILES.get("logo",None)
                org_data["logo"] = logo 
                org = Role.objects.get(name="organization")
                yushi_user.role = org
                Organization.objects.create(**org_data)
            else:
                return resultResponse(700,formRes.errors)
        yushi_user.save()
        return resultResponse()

class UserFileAPIView(APIView):

    def get(self,request,*args, **kwargs):
        _files = UserFile.objects.all().order_by("_id")
        page_num = request.GET.get("page_num",4)
        paginator = Paginator(_files,page_num)
        page = request.GET.get("page",1)
        data = paginator.page(page)
        user_files = []
        for _file in data:
            _file = _file.__dict__
            del _file["_state"]
            _file["create_time"] = "{0:%Y-%m-%d %H:%M:%S}".format(_file["create_time"])
            user_files.append(_file)
        return resultResponse(data=user_files,_list=True)

    def post(self,request,*args, **kwargs):
        _file = request.FILES.get("_file",None)
        if not _file:
            return resultResponse(700,"No File")
        union_id = request.session.get("union_id")
        uploader = YuShiUser.objects.get(union_id=union_id)
        classroom_id = request.data.get("classroom",None)
        formRes = UserFileForm(request.POST)
        if formRes.is_valid():
            file_data = formRes.cleaned_data 
            file_data["uploader"] = uploader
            file_data["_file"] = _file 
            file_data["classroom_id"] = classroom_id 
            UserFile.objects.create(**file_data)
            return resultResponse()
        else:
            return resultResponse(700,formRes.errors)

    

    def delete(self,request,*args, **kwargs):
        pass 

    def put(self,request,*args, **kwargs):
        pass 